﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.UserData;
using QuickTasks.ViewModels;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using LocalSettings;
using System.IO;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using System.Threading;
using QuickTasks.ViewModels.Tables;
using Microsoft.Phone.Tasks;
using Microsoft.Advertising.Mobile.UI;
namespace QuickTasks.Views.FavoritePeople
{
    public partial class contacts : PhoneApplicationPage
    {
      
        int contId = 1;
        bool auto = false;
        private LongListSelector currentSelector;
        public static bool chhk=false;
        List<contactprop> contactslist = new List<contactprop>();
        List<string> ImportedContactList = new List<string>();
        List<string> DeletedContactList = new List<string>();
        IsolatedStorageFile isostore = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream isostream = null;
        List<string> SavedContactList = new List<string>();
        IEnumerable<DependencyObject> cboxes = null;
        XDocument xdoc = null;
        string con = "";
        string PId = "";
        bool backkeypress = false;
        public contacts()
        {
            InitializeComponent();
           
            Loaded += new RoutedEventHandler(contacts_Loaded);



        }
      

        void contacts_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                listcontacts.Loaded += new RoutedEventHandler(listcontacts_Loaded);
                listcontacts.LayoutUpdated += new EventHandler(listcontacts_LayoutUpdated);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in contacts_Loaded event In contacts.xaml page", ex);
            }

        }

        void listcontacts_LayoutUpdated(object sender, EventArgs e)
        {
            SelectSavedContactsInLongList();
        }

        void listcontacts_Loaded(object sender, RoutedEventArgs e)
        {
            PrepareImportedContactList();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (NavigationContext.QueryString.TryGetValue("con", out con))
            {
            }
            if (NavigationContext.QueryString.TryGetValue("PId", out PId))
            {
                con = "1";
            }
            if (con == "1")
            {
                ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                b.IsEnabled = false;
            }
            Contacts objContacts = new Contacts();

            objContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(objContacts_SearchCompleted);

            objContacts.SearchAsync(string.Empty, FilterKind.None, null);

        }


        public void PrepareImportedContactList()
        {

            SavedContactList.Clear();
            string DefaultPlace = "";
            if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
            {
                DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
            }
            else
            {
                DefaultPlace = "1";
            }
            using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
            {

                if (DefaultPlace == "1")
                {
                    var peoples = from i in context.people select i;
                    foreach (var people in peoples)
                    {
                        SavedContactList.Add(people.name);
                    }
                }
                else
                {
                    var peoples = from i in context.people where i.place == DefaultPlace select i;
                    foreach (var people in peoples)
                    {
                        SavedContactList.Add(people.name);
                    }
                }
            }
           
                SelectSavedContactsInLongList();
              
            
            
        }
        
        public void SelectSavedContactsInLongList()
        {
           
                cboxes = GetChildsRecursive(listcontacts);
                
            

            foreach (DependencyObject obj in cboxes.OfType<CheckBox>())
            {

                Type type = obj.GetType();
                if (type.Name == "CheckBox")
                {
                    CheckBox cb = obj as CheckBox;

                    if (SavedContactList.Contains(cb.Tag.ToString()))
                    {
                        auto = true;
                        cb.IsChecked = true;


                    }
                    else
                    {
                        auto = false;
                        cb.IsChecked = false;
                    }
                   


                  
                }
            }
            auto = false;
        }
        public void objContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            try
            {
                foreach (var result in e.Results)
                {
                    QuickTasks.ViewModels.contactprop p = new ViewModels.contactprop();
                    p.alphabet = result.DisplayName.ToString().Substring(0, 1);

                    p.contactname = result.DisplayName.ToString();

                    p.contId = contId;

                    var email = result.EmailAddresses.ToArray();
                    var ph = result.PhoneNumbers.ToArray();
                    contId++;
                    if (ph != null)
                    {
                        int k = ph.Count();
                        if (k == 0)
                        {
                        }
                        else
                        {
                            foreach (var s in ph)
                            {
                                if (s.Kind.ToString() == "Mobile")
                                    p.mphonenum = s.PhoneNumber;
                                if (s.Kind.ToString() == "Home")
                                    p.hphonenum = s.PhoneNumber;
                                if (s.Kind.ToString() == "Work")
                                    p.wphonenum = s.PhoneNumber;
                            }
                        }
                    }
                    if (email != null)
                    {
                        int k = email.Count();
                        if (k == 0)
                        {
                        }
                        else
                        {
                            foreach (var s in email)
                            {
                                if (s.Kind.ToString() == "Personal")
                                {
                                    p.Personal = s.EmailAddress;
                                }
                                if (s.Kind.ToString() == "work")
                                {
                                    p.work = s.EmailAddress;
                                }
                                if (s.Kind.ToString() == "other")
                                {
                                    p.other = s.EmailAddress;
                                }
                            }
                        }
                    }

                    contactslist.Add(p);
                }

                var contacts = from name in contactslist
                               group name by name.alphabet into c
                               orderby c.Key
                               select new Group<contactprop>(c.Key, c);
                listcontacts.ItemsSource = contacts.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in objContacts_SearchCompleted event In contacts.xaml page", ex);
            }

        }
        

        public static IEnumerable<DependencyObject> GetChildsRecursive(DependencyObject root)
        {
            List<DependencyObject> elts = new List<DependencyObject>();
            try
            {
                elts.Add(root);

                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
                {
                    elts.AddRange(GetChildsRecursive(VisualTreeHelper.GetChild(root, i)));
                }
            }
            catch (Exception ex)
            {
                throw new FormatException(ex.Message);
            }
            return elts;
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            
                if (DeletedContactList != null)
                {
                    foreach (string str in DeletedContactList)
                    {
                        var con = from p in contactslist where p.contactname.ToString() == str select p;
                        if (con.Count() > 0)
                        {
                            foreach (var item in con)
                            {
                                try
                                {
                                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                                    {

                                        int id = 1;
                                        IQueryable<people> favoriteid = from i in context.people where i.name == item.contactname select i;
                                        people peo = favoriteid.FirstOrDefault();
                                        context.people.DeleteOnSubmit(peo);
                                        context.SubmitChanges();

                                    }

                                }
                                catch (Exception ex)
                                {
                                    Exceptions.SaveOrSendExceptions("Exception in ApplicationBarIconButton_Click event In contacts.xaml page", ex);
                                }
                            }
                        }
                    }
                }
                if (ImportedContactList != null)
                {
                    if (SavedContactList.Count > 9)
                    {
                        MessageBoxResult resultpeople = MessageBox.Show("Buy full version to add more contacts.press ok to buy", "UPGRADE TO FULL VERSION", MessageBoxButton.OKCancel);
                        if (resultpeople == MessageBoxResult.OK)
                        {
                            MarketplaceDetailTask task = new MarketplaceDetailTask();
                            task.ContentType = MarketplaceContentType.Applications;
                            task.ContentIdentifier = "1003425a-0db9-445a-a2e7-6a36074573c5";
                            task.Show();
                        }
                    }
                    else
                    {
                        foreach (string str in ImportedContactList)
                        {
                            string exist = string.Empty;
                            var con = from p in contactslist where p.contactname.ToString() == str select p;


                            foreach (var item in con)
                            {
                                try
                                {

                                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                                    {



                                        var addressid = from i in context.people where i.mobile == item.mphonenum select i;

                                        foreach (var rep in addressid)
                                        {

                                            exist = "true";
                                        }
                                        string s = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                                        if (exist != "true")
                                        {


                                            int id = 1;
                                            var favoriteid = from i in context.people orderby i.id descending select i;
                                            foreach (var ele in favoriteid)
                                            {
                                                id = ele.id;
                                                id++;
                                                break;
                                            }
                                            people p = new people()
                                            {
                                                id = id,
                                                name = item.contactname,
                                                mobile = item.mphonenum,
                                                home = item.hphonenum,
                                                mwork = item.wphonenum,
                                                other = item.other,
                                                work = item.work,
                                                personal = item.Personal,
                                                place = IsolatedSettings.getSettingsStringValue("DefaultPlace")
                                            };
                                            context.people.InsertOnSubmit(p);
                                            context.SubmitChanges();



                                        }
                                    }
                                }

                                catch (Exception ex)
                                {
                                    Exceptions.SaveOrSendExceptions("Exception in ApplicationBarIconButton_Click event In contacts.xaml page", ex);
                                }
                            }

                        }
                    }
                    NavigationService.GoBack();
               
            }
           
        }
        public void check()
        {

            if (auto == false)
            {

               
                    cboxes = GetChildsRecursive(listcontacts);
                   
                

                ImportedContactList.Clear();
                foreach (DependencyObject obj in cboxes.OfType<CheckBox>())
                {

                    Type type = obj.GetType();
                    if (type.Name == "CheckBox")
                    {
                        CheckBox cb = obj as CheckBox;
                        if (cb.IsChecked == true)
                        {
                            if (!SavedContactList.Contains(cb.Tag.ToString()))
                            {
                                SavedContactList.Add(cb.Tag.ToString());
                                
                            }
                            ImportedContactList.Add(cb.Tag.ToString());
                        }

                    }

                }
            }

        }
        private void chkContacts_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox ck = sender as CheckBox;
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    string DefaultPlace = "";
            if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
            {
                DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
            }
            else
            {
                DefaultPlace = "1";
            }
                    var peoples = from i in context.people where i.name == ck.Tag.ToString() && i.place!=DefaultPlace  select i;
                    if (peoples.Count() > 0)
                    {
                        MessageBoxResult resultLocService = MessageBox.Show("contact is already added in some other location","contacts", MessageBoxButton.OKCancel);
                        if (resultLocService == MessageBoxResult.OK)
                        {
                            chhk = true;
                            ck.IsChecked = false;
                            return;
                        }
                        else
                        {
                            chhk = true;
                            ck.IsChecked = false;
                            return;
                        }
                    }
                }

                if (con == "1")
                {

                    check();
                    if (ImportedContactList != null)
                    {

                        foreach (string str in ImportedContactList)
                        {
                            string exist = string.Empty;
                            var con1 = from p in contactslist where p.contId.ToString() == str select p;


                            foreach (var item in con1)
                            {

                                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                                {


                                    var addressid = from i in context.people where i.mobile == item.mphonenum select i;

                                    foreach (var rep in addressid)
                                    {

                                        exist = "true";
                                    }

                                    if (exist != "true")
                                    {

                                        int id = 1;
                                        IQueryable<people> favoriteid = from i in context.people where i.id.ToString() == PId select i;
                                        if (item.mphonenum == "" && item.hphonenum == "" && item.wphonenum == "")
                                        {
                                            people peop = favoriteid.FirstOrDefault();
                                            context.people.DeleteOnSubmit(peop);
                                            context.SubmitChanges();

                                        }
                                        else
                                        {
                                            people peop = favoriteid.FirstOrDefault();
                                            {
                                                if (item.mphonenum != null) peop.mobile = item.mphonenum;
                                                if (item.hphonenum != null) peop.home = item.hphonenum;
                                                if (item.wphonenum != null) peop.mwork = item.wphonenum;
                                                if (item.other != null) peop.other = item.other;
                                                if (item.work != null) peop.work = item.work;
                                                if (item.Personal != null) peop.personal = item.Personal;
                                            };
                                            context.SubmitChanges();

                                            backkeypress = true;

                                        }

                                    }

                                }



                            }

                        }

                        NavigationService.GoBack();
                    }
                }
                else
                {

                    check();

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in chkContacts_Checked event In contacts.xaml page", ex);
            }
        }

       
        public class Group<T> : IEnumerable<T>
        {
            public Group(string name, IEnumerable<T> items)
            {
                this.Title = name;
                this.Items = new List<T>(items);
            }

            public override bool Equals(object obj)
            {
                Group<T> that = obj as Group<T>;

                return (that != null) && (this.Title.Equals(that.Title));
            }

            public string Title
            {
                get;
                set;
            }

            public IList<T> Items
            {
                get;
                set;
            }

            #region IEnumerable<T> Members

            public IEnumerator<T> GetEnumerator()
            {
                return this.Items.GetEnumerator();
            }

            #endregion

            #region IEnumerable Members

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return this.Items.GetEnumerator();
            }

            #endregion
        }

        public void Unchecked()
        {
              if (auto == false)
            {
                  
            IEnumerable<DependencyObject> cboxes = GetChildsRecursive(listcontacts);

            foreach (DependencyObject obj in cboxes.OfType<CheckBox>())
            {

                Type type = obj.GetType();
                if (type.Name == "CheckBox")
                {
                    CheckBox cb = obj as CheckBox;

                    if (SavedContactList.Contains(cb.Tag.ToString()))
                    {
                        if (cb.IsChecked == false)
                        {
                            if (ImportedContactList.Contains(cb.Tag.ToString()))
                                ImportedContactList.Remove(cb.Tag.ToString());
                            else
                                DeletedContactList.Add(cb.Tag.ToString());
                            SavedContactList.Remove(cb.Tag.ToString());
                            

                        }
                    }

                }
            }
            }

        }
        public void Delete()
        {
            try
            {
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    int id = 1;
                    IQueryable<people> favoriteid = from i in context.people where i.id.ToString() == PId select i;
                    people peo = favoriteid.FirstOrDefault();
                    context.people.DeleteOnSubmit(peo);
                    context.SubmitChanges();

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in Delete method In contacts.xaml page", ex);
            }

        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            try
            {
                if (con == "1")
                {
                    if (backkeypress == false)
                    {
                        Delete();
                        if (NavigationService.CanGoBack)
                        {
                            NavigationService.GoBack();

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in OnBackKeyPress event In contacts.xaml page", ex);
            }
        }

        private void chkContacts_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (chhk == true)
                {
                    chhk = false;
                    return;
                }
                else
                {
                    Unchecked();
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in chkContacts_Unchecked event In contacts.xaml page", ex);
            }
              
        }


    }
}



